<?php 
namespace Users\Controller;
use Admin\Controller\AdminbaseController;
use Think\Upload;
use Vendor\ThinkImage\ThinkImage;

class HeadController extends AdminbaseController{
	
	protected $m;
	
	function _initialize() {
		parent::_initialize();
		$this->m = D('Users');
	}
	
	public function index(){
		$this->uid = $this->curUser['uid'];
		$this->display();
	}
	
	//上传头像
	public function uploadImg(){
		$upload = new Upload();	// 实例化上传类
		$upload->rootPath  =  './Uploads/avatar/'; // 设置附件上传根目录
		//头像目录地址
		$path = './Uploads/avatar/';
		$info = $upload->upload();
		if(!$info) {						// 上传错误提示错误信息
			$this->ajaxReturn(array('status'=>0,'info'=>$upload->getError()));
		}else{
			$file = $info['Filedata'];
			// 上传成功 获取上传文件信息
			$temp_size = getimagesize($path.$file['savepath'].$file['savename']);
			if($temp_size[0] < 100 || $temp_size[1] < 100){//判断宽和高是否符合头像要求
				$this->ajaxReturn(array('status'=>0,'info'=>'图片宽或高不得小于100px！'));
			}
			$this->ajaxReturn(array('status'=>1,'path'=>__ROOT__.'/Uploads/avatar/'.$file['savepath'].$file['savename']));
		}
	}
	
	//裁剪并保存用户头像
	public function cropImg(){
		//图片裁剪数据
		$params = I('post.');						//裁剪参数
		if(!isset($params) && empty($params)){
			$this->error('参数错误！');
		}
		
	
		//头像目录地址
		$path = './Uploads/avatar/';
		$savepath = '/Uploads/avatar/';
		//要保存的图片
		$real_path = $path.'avatar'.$params['uid'].'.jpg';
		//临时图片地址
		$pic_path = '.'.$params['src'];

		//实例化裁剪类
		$Think_img = new ThinkImage(THINKIMAGE_GD);
		//裁剪原图得到选中区域
		$Think_img->open($pic_path)->crop($params['w'],$params['h'],$params['x'],$params['y'])->save($real_path);
		//生成缩略图
		$Think_img->open($real_path)->thumb(100,100, 1)->save($path.'avatar'.$params['uid'].'_100.jpg');
		$Think_img->open($real_path)->thumb(60,60, 1)->save($path.'avatar'.$params['uid'].'_60.jpg');
		$Think_img->open($real_path)->thumb(30,30, 1)->save($path.'avatar'.$params['uid'].'_30.jpg');
		
		$this->saveavatar($params['uid'],$savepath.'avatar'.$params['uid'].'_100.jpg');
		
		$this->success('上传头像成功');
	}
	
	public function saveavatar($uid,$avater){
		$data = array(
			'uid' =>$uid,
			'avater' => $avater,
			'update_time' => Date('Y-m-d H:i:s')
		);
		$this->m->save($data);
	}
}
?>